# Makefile for cnix

ROOTDIR = $(shell pwd)

AS := as
LD := ld
CC := gcc

LDFLAGS := -r
CFLAGS	= -Wall -O2 -fstrength-reduce \
	 -finline-functions -fno-builtin -nostdinc -nostdlib -nodefaultlibs \
	 -I$(ROOTDIR)/include -DCNIX
MKFLAGS := -C

COMP_BUILD_DIR = $(ROOTDIR)/build

export AS LD CC LDFLAGS CFLAGS CPP MKFLAGS COMP_BUILD_DIR ROOTDIR

all:	fdimg

SUBDIRS := driver fs net mm kernel init

ARCHIVES := $(foreach ele, $(SUBDIRS), $(COMP_BUILD_DIR)/$(ele)/$(ele).tmp.o)

config:
	@echo "#ifndef MOD_CONFIG_H" > ./include/cnix/modconfig.h
	@echo "" >> ./include/cnix/modconfig.h
	@grep '^[^#]' Module.cfg | sed 's/\(.\+\) = y/#define \1/' >> ./include/cnix/modconfig.h
	@echo "" >> ./include/cnix/modconfig.h
	@echo "#endif" >> ./include/cnix/modconfig.h

fdimg:	boot/bootsect tools/system tools/makeimg
	@objcopy -O binary -R .note -R .comment tools/system tools/kernel
	tools/makeimg boot/bootsect tools/kernel $@
	tools/ndisasm -b32 tools/kernel > System.asm
	rm -f tools/kernel
	sync

hdimg:	boot/boot tools/system
	@objcopy -O binary -R .note -R .comment tools/system tools/kernel
	cat boot/boot tools/kernel > $@
	rm -f tools/kernel
	sync

boot/bootsect: boot/bootsect.o
	(cd boot; make bootsect)

boot/boot: boot/boot.o
	(cd boot; make boot)

boot/head.o: boot/head.S
	(cd boot; make head.o)

tools/makeimg:
	(cd tools; make)

tools/system: $(ARCHIVES) boot/head.o 
	@$(LD) -T cnix.lds boot/head.o  $(ARCHIVES) -o tools/system 
	@nm tools/system | grep -v '\(compiled\)\|\(\.o$$\)\|\( [aU] \)\|\(\.\.ng$$\)\|\(LASH[RL]DI\)'| sort > System.map

.PHONY:	$(ARCHIVES)
$(ARCHIVES): $(SUBDIRS)

.PHONY: $(SUBDIRS)
$(SUBDIRS):
	@if [ ! -d $(COMP_BUILD_DIR)/$@ ]; then mkdir -p $(COMP_BUILD_DIR)/$@ ; fi
	@make  $(MKFLAGS) $@ COMPONENT=$@

dep:
	make -C driver dep COMPONENT=driver
clean:
	rm -f fdimg hdimg System.map System.asm tools/system
	(cd boot; make clean COMPONENT=boot)
	(cd init; make clean COMPONENT=init) 
	(cd driver; make clean COMPONENT=driver)
	(cd mm;make clean COMPONENT=mm)
	(cd fs;make clean COMPONENT=fs)
	(cd kernel; make clean COMPONENT=kernel)
	(cd net; make clean COMPONENT=net)
	(cd include/asm; rm -f .*.swp *~)
	(cd include/cnix; rm -f .*.swp *~)
